// 现代化武汉大学官网交互功能
class WHUWebsite {
    constructor() {
        this.currentSlide = 0;
        this.carouselInterval = null;
        this.init();
    }

    init() {
        this.setupCarousel();
        this.setupModal();
        this.setupScrollEffects();
        this.setupCounterAnimation();
        this.setupNavigation();
        this.setupSearch();
    }

    // 轮播图功能
    setupCarousel() {
        const carousel = document.querySelector('.carousel');
        const items = document.querySelectorAll('.carousel-item');
        const indicators = document.querySelectorAll('.indicator');
        const prevBtn = document.querySelector('.carousel-prev');
        const nextBtn = document.querySelector('.carousel-next');

        if (!carousel || items.length === 0) return;

        const totalSlides = items.length;

        // 显示指定幻灯片
        this.showSlide = (index) => {
            this.currentSlide = (index + totalSlides) % totalSlides;
            carousel.style.transform = `translateX(-${this.currentSlide * 100}%)`;
            
            // 更新指示器
            indicators.forEach((indicator, i) => {
                indicator.classList.toggle('active', i === this.currentSlide);
            });
        };

        // 下一张幻灯片
        this.nextSlide = () => {
            this.showSlide(this.currentSlide + 1);
        };

        // 上一张幻灯片
        this.prevSlide = () => {
            this.showSlide(this.currentSlide - 1);
        };

        // 绑定事件
        prevBtn?.addEventListener('click', this.prevSlide);
        nextBtn?.addEventListener('click', this.nextSlide);

        // 指示器点击事件
        indicators.forEach((indicator, index) => {
            indicator.addEventListener('click', () => this.showSlide(index));
        });

        // 自动轮播
        this.startAutoPlay();

        // 鼠标悬停暂停
        const carouselContainer = document.querySelector('.carousel-container');
        carouselContainer?.addEventListener('mouseenter', () => {
            this.stopAutoPlay();
        });

        carouselContainer?.addEventListener('mouseleave', () => {
            this.startAutoPlay();
        });

        // 触摸滑动支持
        let startX = 0;
        carouselContainer?.addEventListener('touchstart', (e) => {
            startX = e.touches[0].clientX;
            this.stopAutoPlay();
        });

        carouselContainer?.addEventListener('touchend', (e) => {
            const endX = e.changedTouches[0].clientX;
            const diff = startX - endX;
            
            if (Math.abs(diff) > 50) {
                if (diff > 0) {
                    this.nextSlide();
                } else {
                    this.prevSlide();
                }
            }
            
            this.startAutoPlay();
        });
    }

    startAutoPlay() {
        this.stopAutoPlay();
        this.carouselInterval = setInterval(() => this.nextSlide(), 5000);
    }

    stopAutoPlay() {
        if (this.carouselInterval) {
            clearInterval(this.carouselInterval);
            this.carouselInterval = null;
        }
    }

    // 模态框功能
    setupModal() {
        const loginBtn = document.getElementById('loginBtn');
        const loginModal = document.getElementById('loginModal');
        const closeBtn = document.querySelector('.close');
        const tabBtns = document.querySelectorAll('.tab-btn');
        const loginForm = document.querySelector('.login-form');

        if (!loginBtn || !loginModal) return;

        // 打开模态框
        loginBtn.addEventListener('click', () => {
            loginModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        });

        // 关闭模态框
        const closeModal = () => {
            loginModal.style.display = 'none';
            document.body.style.overflow = '';
        };

        closeBtn?.addEventListener('click', closeModal);

        // 点击外部关闭
        loginModal.addEventListener('click', (e) => {
            if (e.target === loginModal) {
                closeModal();
            }
        });

        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && loginModal.style.display === 'flex') {
                closeModal();
            }
        });

        // 选项卡切换
        tabBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                tabBtns.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
            });
        });

        // 表单提交
        loginForm?.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleLogin();
        });
    }

    handleLogin() {
        const form = document.querySelector('.login-form');
        const username = form.querySelector('input[type="text"]').value;
        const password = form.querySelector('input[type="password"]').value;
        const activeTab = document.querySelector('.tab-btn.active').dataset.type;

        if (!username || !password) {
            this.showNotification('请输入用户名和密码', 'error');
            return;
        }

        // 模拟登录请求
        this.showNotification('登录中...', 'info');
        
        setTimeout(() => {
            this.showNotification(`欢迎回来，${username}！`, 'success');
            document.getElementById('loginModal').style.display = 'none';
            document.body.style.overflow = '';
            form.reset();
        }, 1500);
    }

    // 滚动效果
    setupScrollEffects() {
        const backToTop = document.getElementById('backToTop');
        const header = document.querySelector('header');

        // 返回顶部按钮
        window.addEventListener('scroll', () => {
            const scrollY = window.scrollY;
            
            // 显示/隐藏返回顶部按钮
            if (backToTop) {
                if (scrollY > 300) {
                    backToTop.classList.add('visible');
                } else {
                    backToTop.classList.remove('visible');
                }
            }

            // 头部阴影效果
            if (header) {
                if (scrollY > 50) {
                    header.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.1)';
                } else {
                    header.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
                }
            }
        });

        // 返回顶部功能
        backToTop?.addEventListener('click', () => {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });

        // 导航栏高亮
        this.setupNavHighlight();
    }

    setupNavHighlight() {
        const sections = document.querySelectorAll('section');
        const navLinks = document.querySelectorAll('.nav-link');

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const id = entry.target.getAttribute('id');
                    navLinks.forEach(link => {
                        link.classList.remove('active');
                        if (link.getAttribute('href') === `#${id}`) {
                            link.classList.add('active');
                        }
                    });
                }
            });
        }, {
            threshold: 0.5,
            rootMargin: '-20% 0px -20% 0px'
        });

        sections.forEach(section => {
            observer.observe(section);
        });
    }

    // 数字计数动画
    setupCounterAnimation() {
        const counters = document.querySelectorAll('.stat-number');
        const statsSection = document.querySelector('.stats-section');

        if (!counters.length || !statsSection) return;

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    counters.forEach(counter => {
                        const target = parseInt(counter.getAttribute('data-count'));
                        this.animateCounter(counter, target);
                    });
                    observer.unobserve(entry.target);
                }
            });
        }, { threshold: 0.5 });

        observer.observe(statsSection);
    }

    animateCounter(element, target) {
        let current = 0;
        const increment = target / 100;
        const duration = 2000;
        const stepTime = duration / 100;

        const timer = setInterval(() => {
            current += increment;
            if (current >= target) {
                element.textContent = target.toLocaleString();
                clearInterval(timer);
            } else {
                element.textContent = Math.floor(current).toLocaleString();
            }
        }, stepTime);
    }

    // 导航功能
    setupNavigation() {
        // 平滑滚动
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', (e) => {
                e.preventDefault();
                const targetId = anchor.getAttribute('href');
                if (targetId === '#') return;

                const targetElement = document.querySelector(targetId);
                if (targetElement) {
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });

        // 移动端菜单
        this.setupMobileMenu();
    }

    setupMobileMenu() {
        // 在小屏幕设备上添加移动端菜单功能
        if (window.innerWidth <= 768) {
            const nav = document.querySelector('.nav-menu');
            if (!nav) return;

            // 可以在这里添加移动端菜单切换功能
        }
    }

    // 搜索功能
    setupSearch() {
        const searchInput = document.getElementById('searchInput');
        
        searchInput?.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.performSearch();
            }
        });
    }

    performSearch() {
        const searchInput = document.getElementById('searchInput');
        const query = searchInput?.value.trim();

        if (!query) {
            this.showNotification('请输入搜索关键词', 'warning');
            return;
        }

        // 模拟搜索
        this.showNotification(`搜索: ${query}`, 'info');
        
        // 在实际应用中，这里会跳转到搜索结果页面
        console.log('执行搜索:', query);
    }

    // 通知系统
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <span>${message}</span>
            <button class="notification-close">&times;</button>
        `;

        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${this.getNotificationColor(type)};
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 3000;
            display: flex;
            align-items: center;
            gap: 10px;
            max-width: 400px;
            animation: slideIn 0.3s ease;
        `;

        // 关闭按钮
        const closeBtn = notification.querySelector('.notification-close');
        closeBtn.style.cssText = `
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        `;

        closeBtn.addEventListener('click', () => {
            notification.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        });

        document.body.appendChild(notification);

        // 自动消失
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }
        }, 4000);
    }

    getNotificationColor(type) {
        const colors = {
            info: '#3498db',
            success: '#27ae60',
            warning: '#f39c12',
            error: '#e74c3c'
        };
        return colors[type] || colors.info;
    }
}

// 服务门户菜单
function showServiceMenu() {
    const services = [
        '信息门户', '教务系统', '图书馆', '校园卡',
        '网络教学', '就业信息', '财务系统', '后勤服务'
    ];
    
    alert(`服务门户功能:\n${services.join('\n')}`);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .fade-in {
        animation: fadeIn 0.6s ease;
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
`;
document.head.appendChild(style);

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new WHUWebsite();
    
    // 添加加载动画
    document.body.classList.add('fade-in');
});

// 导出供全局使用
window.WHUWebsite = WHUWebsite;
window.showServiceMenu = showServiceMenu;